<template>
  <div class="article-preview">
    <div class="article-meta">
      <nuxt-link
        :to="{ name: 'profile', params: { username: art.author.username } }"
      >
        <img :src="art.author.image" />
      </nuxt-link>
      <div class="info">
        <nuxt-link
          :to="{ name: 'profile', params: { username: art.author.username } }"
          class="author"
        >
          {{ art.author.username }}
        </nuxt-link>
        <span class="date">{{ art.createdAt | date }}</span>
      </div>
      <button
        class="btn btn-outline-primary btn-sm pull-xs-right"
        :class="art.favorited ? 'active' : ''"
        :disabled="favDisabled"
        @click="handleFavorite(art)"
      >
        <i class="ion-heart"></i> {{ art.favoritesCount }}
      </button>
    </div>
    <nuxt-link
      :to="{ name: 'article', params: { slug: art.slug } }"
      class="preview-link"
    >
      <h1>{{ art.title }}</h1>
      <p>{{ art.body }}</p>
      <span>Read more...</span>
    </nuxt-link>
  </div>
</template>

<script>
import { favoriteArticle, unfavoriteArticle } from '@/api/article'

export default {
  name: 'Arttie',
  props: {
    art: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      favDisabled: false,
    }
  },
  methods: {
    handleFavorite(art) {
      if (this.favDisabled) {
        return
      }
      const fav = art.favorited ? unfavoriteArticle : favoriteArticle
      this.favDisabled = true
      art.favoritesCount += art.favorited ? -1 : 1
      art.favorited = !art.favorited
      fav(art.slug).then(() => {
        this.favDisabled = false
      })
    },
  },
}
</script>

<style scoped></style>
